#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <printk.h>
#include <utils.h>
#include "fs-poll.h"

static void fs_cb(ev_fs_t *req)
{
    if (req->result == 0)
    {
        struct file_poll *fp = container_of(req, struct file_poll, req);
        ev_stat_t *st = req->data;

        assert(st != NULL);
        if (st->st_mtim.tv_sec != fp->msec)
            fp->poll_cb(fp);
    }

    uv_fs_req_cleanup(req);
}
static void fs_poll_timer_cb(void *data)
{
    struct file_poll *fp = data;
    int r;

    if (fp->req.path) return;

    r = uv_fs_stat(fp->loop, &fp->req, fp->path, fs_cb);
    if (r < 0)
        APP_PE("<LOG>: get stat error!\n");
}

int fs_poll_add(struct file_poll *fp, ev_loop_t *loop, const char *path, u32 interval,
                void (*poll_cb)(struct file_poll *fp))
{
    int r;

    fp->loop = loop;
    fp->poll_cb = poll_cb;

    r = uv_fs_stat(loop, &fp->req, path, NULL);
    if (r < 0)
    {
        uv_fs_req_cleanup(&fp->req);
        return r;
    }
    fp->msec = ((ev_stat_t *)fp->req.data)->st_mtim.tv_sec;
    uv_fs_req_cleanup(&fp->req);

    fp->path = svc__strdup(path);
    soft_timer_add(loop, &fp->poll_timer, "fs_poll", fs_poll_timer_cb, fp);
    soft_timer_start(&fp->poll_timer, interval, interval);
    return 0;
}
void fs_poll_del(struct file_poll *fp)
{
    soft_timer_del(&fp->poll_timer);
    uv_fs_req_cleanup(&fp->req);
    kfree((void *)fp->path);
}

